#include <iostream>
#include <thread>
#include <utility>
#include <vector>
#include <string>
#include "Mutexed.hpp"

// 自定义的类
class Counter {
public:
    int value;
    std::string name;

    Counter(const int v, std::string n) : value(v), name(std::move(n)) {}

    void increment() {
        ++value;
    }

    void reset() {
        value = 0;
    }
};

int main() {
    // 创建一个包装自定义类的线程安全对象
    auto safe_counter = make_mutex<Counter>(Counter(0, "MyCounter"));

    // 多线程操作自定义类
    std::vector<std::thread> threads;
    threads.reserve(5);
for (int i = 0; i < 5; ++i) {
        threads.emplace_back([&safe_counter]() {
            for (int j = 0; j < 100; ++j) {
                safe_counter->with_lock([](Counter& counter) {
                    counter.increment();
                });
            }
        });
    }

    // 等待所有线程完成
    for (auto& t : threads) {
        t.join();
    }

    // 使用 Guard 访问自定义类
    {
        auto guard = safe_counter->lock();
        std::cout << "Counter " << guard->name
                  << " final value: " << guard->value << std::endl;

        guard->reset();  // 重置计数器
        std::cout << "After reset: " << guard->value << std::endl;
    }

    return 0;
}
